
package com.practica.superTrivia;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import static com.practica.superTrivia.Consts.*;

public class Settings extends Activity {
    final static public int QUESTION_PREFERENCES_DIALOG = 2;
    final static public int QUESTION_SERVER_DIALOG = 3;	
    private String email;
    private String emailFriend;
    
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);    
       
        setContentView(R.layout.settings);
    
        restoreSettings();
        
        final Button buttonSelectPreferences = (Button) findViewById(R.id.buttonSelectPreferences);
        
    	buttonSelectPreferences.setOnClickListener(new View.OnClickListener() {
		    public void onClick(View v) {
			    // TODO Auto-generated method stub
		    	showDialog(QUESTION_PREFERENCES_DIALOG);
		    }
    	});
    
    	
	    //Asignamos al spinner un adaptador con los items guardados en server_array
	    Spinner spinner = (Spinner) findViewById(R.id.spinnerQuestionsServer);
	    ArrayAdapter <CharSequence> adapter = ArrayAdapter.createFromResource(
	    		this, R.array.server_array, android.R.layout.simple_spinner_item);
	    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	    spinner.setAdapter(adapter);
	    
	    //Aplicamos el MyOnItemSelectedListener al spinner
	    spinner.setOnItemSelectedListener(new MyOnItemSelectedListener());
    }
    
	@Override
	protected void onDestroy() {
		super.onDestroy();
		
		saveSettings();
	}

	private void restoreSettings()
    {
		
    	SharedPreferences preferences = getSharedPreferences(PREFERENCES, Context.MODE_PRIVATE);
    	EditText textName = (EditText) findViewById(R.id.textFieldUserName);
    	EditText textEmail = (EditText) findViewById(R.id.textFieldEmailAddress);
        TextView tv = (TextView) findViewById(R.id.textView2);
    	textName.setText(preferences.getString(PREFERENCES_USER_NAME, ""));
    	textEmail.setText(preferences.getString(PREFERENCES_EMAIL, ""));
        tv.setText(preferences.getString(PREFERENCES_SET, "Preferences not set"));
    }
    
    private void saveSettings()
    {
    	SharedPreferences preferences = getSharedPreferences(PREFERENCES, Context.MODE_PRIVATE);
    	EditText textUser = (EditText) findViewById(R.id.textFieldUserName);
    	EditText textEmail = (EditText) findViewById(R.id.textFieldEmailAddress);
    	
    	Editor editor = preferences.edit();
    	editor.putString(PREFERENCES_USER_NAME, textUser.getText().toString());
    	editor.putString(PREFERENCES_EMAIL, textEmail.getText().toString());
    	editor.commit();
    	
    }
     
    @Override
    protected Dialog onCreateDialog(int id) {
    // TODO Auto‐generated method stub
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    switch(id) {
    case QUESTION_PREFERENCES_DIALOG:
    	final CharSequence[] items = {getResources().getString(R.string.sports), 
    			getResources().getString(R.string.literature), 
    			getResources().getString(R.string.science),
    			getResources().getString(R.string.movies),
    			getResources().getString(R.string.history)
    			};

        final boolean[] state = new boolean[5];

    	SharedPreferences preferences = getSharedPreferences(PREFERENCES, Context.MODE_PRIVATE);

        state[0] = preferences.getBoolean(PREFERENCES_QUESTION_TYPE_0, true);
        state[1] = preferences.getBoolean(PREFERENCES_QUESTION_TYPE_1, true);
        state[2] = preferences.getBoolean(PREFERENCES_QUESTION_TYPE_2, true);
        state[3] = preferences.getBoolean(PREFERENCES_QUESTION_TYPE_3, true);
        state[4] = preferences.getBoolean(PREFERENCES_QUESTION_TYPE_4, true);
        
    	builder.setTitle(getResources().getString(R.string.questionsPreferences));
    	
    	builder.setMultiChoiceItems(items, state, new DialogInterface.OnMultiChoiceClickListener() {
			public void onClick(DialogInterface dialog, int which,
					boolean isChecked) {
				state[which] = isChecked;
			}
    	});
    	
        builder.setPositiveButton(getResources().getString(R.string.ok), new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
            	
            	SharedPreferences preferences = getSharedPreferences(PREFERENCES, Context.MODE_PRIVATE);
            	
            	Editor editor = preferences.edit();
            	editor.putBoolean(PREFERENCES_QUESTION_TYPE_0, state[0]);
            	editor.putBoolean(PREFERENCES_QUESTION_TYPE_1, state[1]);
            	editor.putBoolean(PREFERENCES_QUESTION_TYPE_2, state[2]);
            	editor.putBoolean(PREFERENCES_QUESTION_TYPE_3, state[3]);
            	editor.putBoolean(PREFERENCES_QUESTION_TYPE_4, state[4]);
            	editor.putString(PREFERENCES_SET, "Preferences set");
            	editor.commit();
            }
        });
        builder.setNegativeButton(getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                 dialog.cancel();
            }
        });
	    break;
    }
    return builder.create();
    }    

    protected void onPrepareDialog(int id, Dialog dialog){
    	onCreateDialog(id);
    }
    
    
    //Clase auxiliar para implementar el Spinner 
    public class MyOnItemSelectedListener implements OnItemSelectedListener {

        public void onItemSelected(AdapterView<?> parent,
            View view, int pos, long id) {
          Toast.makeText(parent.getContext(), "Server: " +
              parent.getItemAtPosition(pos).toString(), Toast.LENGTH_LONG).show();
        }

        @SuppressWarnings("rawtypes")
		public void onNothingSelected(AdapterView parent) {
          // Do nothing.
        }
    }
    
    public void addFriendButtonClick()
    {
    	TextView tx = (TextView)findViewById(R.id.textFieldEmailAddress);
    	TextView txF = (TextView)findViewById(R.id.textFieldFriendEmail);
    	this.email = tx.getText().toString();
    	this.emailFriend = txF.getText().toString();
    	addFriend();
    }
    
    
    
    private void addFriend() {
		Handler handler = new Handler() {
			public void handleMessage(Message message) {
				switch (message.what) {
				case HttpConnection.DID_START: {
					Log.d("Añadir Amigo", "Starting Connection");
					break;
				}
				case HttpConnection.DID_SUCCEED: {
					//No hacemos nada
					break;
				}
				case HttpConnection.DID_ERROR: {
					Exception e = (Exception) message.obj;
					e.printStackTrace();
					break;
				}
				}
			}
		};
		new HttpConnection(handler) //Es una clase implementada por nosotros
			.post("http://dakon.disca.upv.es:8080/WebServiceTrivial/rest/friends", email, emailFriend);
    }
}
